﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BestEasy.Core
{
    /// <summary>
    /// 实体对象基类
    /// </summary>
    /// <typeparam name="TId">主键类型</typeparam>
    public abstract class EntityBase<TId> : IAggregateRoot
    {
        /// <summary>
        /// 获取或设置该实体标识符
        /// </summary>
        public TId Id { get; set; }

        private readonly List<BusinessRule> _brokenRules = new List<BusinessRule>();

        protected abstract void Validate();

        /// <summary>
        /// 获取不通过验证的业务规则
        /// </summary>
        /// <returns></returns>
        public IEnumerable<BusinessRule> GetBrokenRules()
        {
            _brokenRules.Clear();
            Validate();
            return _brokenRules;
        }
        /// <summary>
        /// 添加不通过的业务规则
        /// </summary>
        /// <param name="businessRule"></param>
        protected void AddBrokenRule(BusinessRule businessRule)
        {
            _brokenRules.Add(businessRule);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as EntityBase<TId>);
        }

        private static bool IsTransient(EntityBase<TId> obj)
        {
            return obj != null && Equals(obj.Id, default(int));
        }

        private Type GetUnproxiedType()
        {
            return GetType();
        }

        public virtual bool Equals(EntityBase<TId> other)
        {
            if (other == null)
                return false;

            if (ReferenceEquals(this, other))
                return true;

            if (!IsTransient(this) &&
                !IsTransient(other) &&
                Equals(Id, other.Id))
            {
                var otherType = other.GetUnproxiedType();
                var thisType = GetUnproxiedType();
                return thisType.IsAssignableFrom(otherType) ||
                        otherType.IsAssignableFrom(thisType);
            }
            return false;
        }

        public override int GetHashCode()
        {
            if (Equals(Id, default(TId)))
                return base.GetHashCode();
            return Id.GetHashCode();
        }

        public static bool operator ==(EntityBase<TId> x, EntityBase<TId> y)
        {
            return Equals(x, y);
        }

        public static bool operator !=(EntityBase<TId> x, EntityBase<TId> y)
        {
            return !(x == y);
        }
    }
}
